package com.css.zfzx.sjcj.modules.hddcGeomorphySvyLine.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.spacedata.vo.SpaceDataParamsVo;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPlanningLine.repository.entity.HddcGeologicalsvyplanninglineEntity;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyLine.repository.HddcGeomorphysvylineNativeRepository;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyLine.repository.HddcGeomorphysvylineRepository;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyLine.repository.entity.HddcGeomorphysvylineEntity;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyLine.service.HddcGeomorphysvylineService;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyLine.viewobjects.HddcGeomorphysvylineQueryParams;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyLine.viewobjects.HddcGeomorphysvylineVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zyb
 * @date 2020-11-27
 */
@Service
public class HddcGeomorphysvylineServiceImpl implements HddcGeomorphysvylineService {

	@Autowired
    private HddcGeomorphysvylineRepository hddcGeomorphysvylineRepository;
    @Autowired
    private HddcGeomorphysvylineNativeRepository hddcGeomorphysvylineNativeRepository;

    @Override
    public JSONObject queryHddcGeomorphysvylines(HddcGeomorphysvylineQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcGeomorphysvylineEntity> hddcGeomorphysvylinePage = this.hddcGeomorphysvylineNativeRepository.queryHddcGeomorphysvylines(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcGeomorphysvylinePage);
        return jsonObject;
    }


    @Override
    public HddcGeomorphysvylineEntity getHddcGeomorphysvyline(String id) {
        HddcGeomorphysvylineEntity hddcGeomorphysvyline = this.hddcGeomorphysvylineRepository.findById(id).orElse(null);
         return hddcGeomorphysvyline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeomorphysvylineEntity saveHddcGeomorphysvyline(HddcGeomorphysvylineEntity hddcGeomorphysvyline) {
        String uuid = UUIDGenerator.getUUID();
        hddcGeomorphysvyline.setUuid(uuid);
        hddcGeomorphysvyline.setCreateUser(PlatformSessionUtils.getUserId());
        hddcGeomorphysvyline.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcGeomorphysvyline.setIsValid("1");
        hddcGeomorphysvyline.setQualityinspectionStatus("0");
        hddcGeomorphysvyline.setExtends10("1");
        this.hddcGeomorphysvylineRepository.save(hddcGeomorphysvyline);
        return hddcGeomorphysvyline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeomorphysvylineEntity updateHddcGeomorphysvyline(HddcGeomorphysvylineEntity hddcGeomorphysvyline) {
        HddcGeomorphysvylineEntity entity = hddcGeomorphysvylineRepository.findById(hddcGeomorphysvyline.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcGeomorphysvyline);
        hddcGeomorphysvyline.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcGeomorphysvyline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcGeomorphysvylineRepository.save(hddcGeomorphysvyline);
        return hddcGeomorphysvyline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcGeomorphysvylines(List<String> ids) {
        List<HddcGeomorphysvylineEntity> hddcGeomorphysvylineList = this.hddcGeomorphysvylineRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcGeomorphysvylineList) && hddcGeomorphysvylineList.size() > 0) {
            for(HddcGeomorphysvylineEntity hddcGeomorphysvyline : hddcGeomorphysvylineList) {
                hddcGeomorphysvyline.setIsValid("0");
                hddcGeomorphysvyline.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeomorphysvyline.setUpdateTime(new Date());
                this.hddcGeomorphysvylineRepository.save(hddcGeomorphysvyline);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcGeomorphysvylineQueryParams queryParams, HttpServletResponse response) {
        List<HddcGeomorphysvylineEntity> yhDisasterEntities = hddcGeomorphysvylineNativeRepository.exportYhDisasters(queryParams);
        List<HddcGeomorphysvylineVO> list=new ArrayList<>();
        for (HddcGeomorphysvylineEntity entity:yhDisasterEntities) {
            HddcGeomorphysvylineVO yhDisasterVO=new HddcGeomorphysvylineVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "微地貌测量线-线", "微地貌测量线-线", HddcGeomorphysvylineVO.class, "微地貌测量线-线.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcGeomorphysvylineVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcGeomorphysvylineVO.class, params);
            List<HddcGeomorphysvylineVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcGeomorphysvylineVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcGeomorphysvylineVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcGeomorphysvylineVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcGeomorphysvylineEntity yhDisasterEntity = new HddcGeomorphysvylineEntity();
            HddcGeomorphysvylineVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcGeomorphysvyline(yhDisasterEntity);
        }
    }
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcGeomorphysvylineEntity> hddcGeomorphysvylineList = this.hddcGeomorphysvylineRepository.queryHddcGeomorphysvylinesByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcGeomorphysvylineList) && hddcGeomorphysvylineList.size() > 0) {
            for(HddcGeomorphysvylineEntity hddcGeomorphysvyline : hddcGeomorphysvylineList) {
                hddcGeomorphysvyline.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeomorphysvyline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcGeomorphysvyline.setIsValid("0");
                this.hddcGeomorphysvylineRepository.save(hddcGeomorphysvyline);
            }
        }
    }

    @Override
    public void deleteByTaskId(List<String> taskIds) {
        List<HddcGeomorphysvylineEntity> hddcGeomorphysvylineList = this.hddcGeomorphysvylineRepository.queryHddcGeomorphysvylinesByTaskId(taskIds);
        if(!PlatformObjectUtils.isEmpty(hddcGeomorphysvylineList) && hddcGeomorphysvylineList.size() > 0) {
            for(HddcGeomorphysvylineEntity hddcGeomorphysvyline : hddcGeomorphysvylineList) {
                hddcGeomorphysvyline.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeomorphysvyline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcGeomorphysvyline.setIsValid("0");
                this.hddcGeomorphysvylineRepository.save(hddcGeomorphysvyline);
            }
        }
    }

    @Override
    public List<HddcGeomorphysvylineEntity> findAll() {
        List<HddcGeomorphysvylineEntity> list=this.hddcGeomorphysvylineRepository.findAll();
        return list;
    }

    @Override
    @Transactional
    public void deleteFileData(SpaceDataParamsVo paramsVo) {
        String provinceName=paramsVo.getProvinceName();
        String cityName=paramsVo.getCityName();
        String areaName=paramsVo.getAreaName();
        String savefilename=paramsVo.getSavefilename();
        hddcGeomorphysvylineRepository.deleteFileData( provinceName, cityName, areaName, savefilename);
    }


    // 批量插入数据库

    @Transactional(rollbackFor = Exception.class)
    public Iterable<HddcGeomorphysvylineEntity> saveHddcGeomorphysvylineList(List<HddcGeomorphysvylineEntity> list ) {
        for (HddcGeomorphysvylineEntity hddcGeomorphysvyline : list) {
            String uuid = UUIDGenerator.getUUID();
            hddcGeomorphysvyline.setUuid(uuid);
            hddcGeomorphysvyline.setCreateUser(PlatformSessionUtils.getUserId());
            hddcGeomorphysvyline.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            hddcGeomorphysvyline.setIsValid("1");
            hddcGeomorphysvyline.setQualityinspectionStatus("0");
            hddcGeomorphysvyline.setExtends10("1");
        }
        //List<HddcGeologicalsvyplanninglineEntity> resultList = hddcGeologicalsvyplanninglineRepository.saveAll(list);
        Iterable<HddcGeomorphysvylineEntity> iterable = hddcGeomorphysvylineNativeRepository.batchSave(list);
        return iterable;
    }

    @Override
    public String judegeParams(String[] datas) {
        String str = "";
        Set<String> set = new HashSet<String>(Arrays.asList(datas));
        if (!set.contains("ID")) {
            str += "ID,";
        }
        if (!set.contains("GeomorphySvyPrjID")) {
            str += "GeomorphySvyPrjID,";
        }
        if (!set.contains("FieldID")) {
            str += "FieldID,";
        }
        if (!set.contains("Name")) {
            str += "Name,";
        }
        if (!set.contains("Profile_AIID")) {
            str += "Profile_AIID,";
        }
        if (!set.contains("Profile_ARWID")) {
            str += "Profile_ARWID,";
        }
        if (!set.contains("Photo_AIID")) {
            str += "Photo_AIID,";
        }
        if (!set.contains("Photo_ARWID")) {
            str += "Photo_ARWID,";
        }
        if (!set.contains("PhotoViewingTo")) {
            str += "PhotoViewingTo,";
        }
        if (!set.contains("Photographer")) {
            str += "Photographer,";
        }
        if (!set.contains("CommentInfo")) {
            str += "CommentInfo,";
        }

        return str;
    }

    @Override
    public void savehddcGeomorphysvylineServiceFromShpFiles(List<List<Object>> list, String provinceName, String cityName, String areaName, String savefilename) {

        if (list != null && list.size() > 0) {
            List<HddcGeomorphysvylineEntity> datas = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                List<Object> obs = list.get(i);
                HddcGeomorphysvylineEntity data = new HddcGeomorphysvylineEntity();
                data.setArea(areaName);
                data.setProvince(provinceName);
                data.setCity(cityName);
                data.setExtends8(savefilename);
                data.setId(obs.get(1).toString());
                data.setGeomorphysvyprjid(obs.get(2).toString());
                data.setFieldid(obs.get(3).toString());
                data.setName(obs.get(4).toString());
                data.setProfileAiid(obs.get(5).toString());
                data.setProfileArwid(obs.get(6).toString());
                data.setPhotoAiid(obs.get(7).toString());
                data.setPhotoArwid(obs.get(8).toString());
                data.setPhotoviewingto(Integer.valueOf(obs.get(9).toString()));
                data.setPhotographer(obs.get(10).toString());
                data.setCommentInfo(obs.get(11).toString());
                data.setExtends16("CGCS2000");
                String pstr = obs.get(0).toString();
                /*String[] ss1 = pstr.split("\\(");
                if (ss1.length == 2) {
                    String[] ss2 = ss1[1].split("\\)");
                    if (ss2.length <= 2) {
                        String spacedata = ss2[0].replace(",", ";").replace(" ", ",");
                        data.setExtends5(spacedata);
                    }
                }*/
                pstr = pstr.replace(")), ((", "#");
                pstr = pstr.replace("), (", "#");
                String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }
                datas.add(data);
                /*for(int j=0;j<obs.size();j++){
                    Object value=obs.
                }*/
            }
            deleteByCreateUser(provinceName,cityName,areaName);
            saveHddcGeomorphysvylineList(datas);
        }

    }

    public void deleteByCreateUser(String provinceName,String cityName,String areaName) {
        String createID = PlatformSessionUtils.getUserId();
        List<HddcGeomorphysvylineEntity> hddcGeomorphysvylineList = this.hddcGeomorphysvylineRepository.queryHddcGeomorphysvylineByCreateuser(createID,provinceName,cityName,areaName);
        if (!PlatformObjectUtils.isEmpty(hddcGeomorphysvylineList) && hddcGeomorphysvylineList.size() > 0) {
            hddcGeomorphysvylineRepository.deleteAll(hddcGeomorphysvylineList);
        }
    }
}
